package com.haoshui.filter;

import com.alibaba.fastjson.JSON;
import com.haoshui.domain.ResponseResult;
import com.haoshui.domain.entity.LoginUser;
import com.haoshui.enums.AppHttpCodeEnum;
import com.haoshui.utils.JwtUtil;
import com.haoshui.utils.RedisCache;
import com.haoshui.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //从request头中获得token
        String token = httpServletRequest.getHeader("token");
        //没有token，直接放行
        if (!StringUtils.hasText(token)) {
            //请求不需要token
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }

        //解析token，得到userID
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //解析失败，token不合法，或者token过期
//            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//            String s = JSON.toJSONString(responseResult);
//            WebUtils.renderString(httpServletResponse, s);
            return;
        }

        //去redis中找出对应的用户信息
        String id = claims.getSubject();
        LoginUser loginUser = redisCache.getCacheObject("bloglogin:" + id);

        //获取用户失败
        if(Objects.isNull(loginUser)){
            //redis里面的账户信息超时
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            String s = JSON.toJSONString(responseResult);
            WebUtils.renderString(httpServletResponse, s);
            return;
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //通过过滤器
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
